﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;
using WebUI.Controls;

namespace WebUI
{
    public partial class Customer : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            base.Page_Load(sender, e);
            if (!IsPostBack)
            {
                Reload();
            }

            if (SessionUser.BranchID != Branches.CurrentBranchID || !SessionUser.Admin)
            {
                btnAddCust.Enabled = false;
                btnAddCustType.Enabled = false;
                btnDeleteCust.Enabled = false;
                btnRemoveCustType.Enabled = false;
                btnEditCust.Enabled = false;
                btnEditCustType.Enabled = false;
                btnResetPwd.Enabled = false;

                btnAddCust.OnClientClick = "";
                btnAddCustType.OnClientClick = "";
                btnDeleteCust.OnClientClick = "";
                btnRemoveCustType.OnClientClick = "";
                btnEditCust.OnClientClick = "";
                btnEditCustType.OnClientClick = "";
                btnResetPwd.OnClientClick = "";
            }
        }

        protected void btnResetPwd_OnClick(object sender, EventArgs e)
        {
            if (hidSelectedCust.Value != "")
            {
                int custID = int.Parse(hidSelectedCust.Value);
                Customers c = new Customers();
                c.LoadByPrimaryKey(custID);
                if (c.RowCount > 0)
                {
                    c.s_Password = Utilities.CreateMD5Hash( Utilities.GetConfigAppSetting("DefaultPassword"));
                    c.Save();

                    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("alert('Reset password successfully!');"), true);
                    lstCustomer.Refresh();

                    updateToolBar.Update();
                }
            }
        }


        const string NO_SELECT = "-999";

        private void Reload()
        {
            hidSelectedGroup.Value = NO_SELECT;
            Customers custs = Customers.GetAllActiveCustomers();
            lstCustomer.Custs = custs;

            GroupList = CustomerType.GetAllActiveCustomerType();
            
            RefreshCustomerGroup();

            RefreshCustomerList();

            updateGroup.Update();

        }

        private void RefreshCustomerList()
        {
            gridFilterPaging.Reset();

            string oldFilter = lstCustomer.Filter;
            int selectedGroup = int.Parse(hidSelectedGroup.Value);

            lstCustomer.Filter = CustomerType.ColumnNames.Deleted + "=0";

            if (hidSelectedGroup.Value != NO_SELECT)
            {
                lstCustomer.Filter += " and " + Customers.ColumnNames.CustomerType + "=" + selectedGroup;
            }
            
            gridFilterPaging.DefaultFilter = lstCustomer.Filter;

            lstCustomer.Refresh();
        }

        

        public String GroupListSessionKey
        {
            get { return ViewState["GroupListSessionKey"] != null ? ViewState["GroupListSessionKey"].ToString() : ""; }
            set { ViewState["GroupListSessionKey"] = value; }
        }

        public CustomerType GroupList
        {
            get { return Session[GroupListSessionKey] != null ? (CustomerType)Session[GroupListSessionKey] : null; }
            set { Session[GroupListSessionKey] = value; }
        }

        public string GetCustEditPageLink()
        {
            return "EditPages/EditCustomer.aspx?key=" + lstCustomer.SourceObjectSessionID;
        }

        public string GetCustInvoiceHistory()
        {
            return "EditPages/InvoiceViewer.aspx?";
        }

        public string GetCustPaymentHistory()
        {
            return "EditPages/PaymentHistViewer.aspx?";
        }

        public string GetGroupEditPageLink()
        {
            return "EditPages/EditCustomerType.aspx?key=" + GroupListSessionKey;
        }

        protected void btnAddCust_OnClick (Object sender, EventArgs e)
        {
            lstCustomer.Refresh();
        }

        protected void RefreshCustomerGroup()
        {
            string oldFilter = GroupList.Filter;
            GroupList.Filter = StockLocation.ColumnNames.Deleted + "=0";

            GroupList.Rewind();
            divGroup.InnerHtml = "";

            for (int i = 0; i < GroupList.RowCount; i++)
            {
                string button = String.Format("<input id='{0}' value='{1}' type='button' onclick='btnGroup_click(this)' style='width:100%; margin-top:4px' GroupID='{2}' {3} />",
                    "btn_" + GroupList.s_ID, GroupList.s_TypeName, GroupList.s_ID, GroupList.s_ID == hidSelectedGroup.Value ? "class='sortButtonSelected'" : "");

                divGroup.InnerHtml += button;

                GroupList.MoveNext();
            }
        }

        protected void btnLoadByGroup_OnClick(object sender, EventArgs e)
        {
            RefreshCustomerList();
        }

        protected void btnRemoveCust_OnClick (object sender, EventArgs e)
        {
            lstCustomer.DeleteCheckedItems();
            RefreshCustomerList();
        }

        protected void  btnPrintCust_OnClick (object sender, EventArgs e)
        {

            CustomerListCtrl printedList = (CustomerListCtrl)LoadControl(@"~/Controls/POSControls/CustomerListCtrl.ascx");
            printedList.AllowPaging = false;
            printedList.AllowSelecting = false;
            printedList.AllowSorting = false;
            printedList.SourceObject = lstCustomer.Custs;
            printedList.Width = new Unit(100, UnitType.Percentage);
            printedList.GridLineStyle = GridLines.Both;
            printedList.GridBorder = BorderStyle.Solid;
            printedList.GridBorderWidth = new Unit(1, UnitType.Pixel);
            printedList.CssClass = "";
            printedList.Refresh();

            Session[PrintKey] = printedList;
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);

            lstCustomer.Refresh();
        }

        protected void btnInvoiceHistory_OnClick(object sender, EventArgs e)
        {
            InvoiceListCtrl ivc = (InvoiceListCtrl)LoadControl(@"~/Controls/POSControls/InvoiceListCtrl.ascx");
            ivc.AllowPaging = true;
            ivc.PageSize = 10;
            ivc.AllowSelecting = false;
            ivc.AllowSorting = false;
            ivc.SourceObject = View_Invoices.GetInvoiceByCustID(int.Parse(hidSelectedCust.Value));
            ivc.Width = new Unit(100, UnitType.Percentage);
            ivc.GridLineStyle = GridLines.Both;
            ivc.GridBorder = BorderStyle.Solid;
            ivc.GridBorderWidth = new Unit(1, UnitType.Pixel);
            ivc.CssClass = "";
            ivc.Refresh();

            Session[PrintKey] = ivc;
            ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showPrintDlg('{0}');", GetPrintPage()), true);
        }



        protected void  btnExcel_OnClick(object sender, EventArgs e)
        {
            Utilities.ExportToExcel(lstCustomer.Custs, "Customer.xls",
                new String[] { "CustomerName", "Company", "Address", "Phone", "Mobile", "Fax", "Email" },
                new String[] { "Customer", "Company", "Address", "Phone", "Mobile", "Fax", "Email" },
                "Customer");
        }

        protected void  btnSearchCust_OnClick(object sender, EventArgs e)
        {
            gridFilterPaging.Reset();
            //if (gridFilterPaging.DefaultFilter != "")
            //    lstCustomer.Filter = gridFilterPaging.DefaultFilter + " and (" + Customers.ColumnNames.CustomerName + " LIKE '%" + txtSearchCust.Text + "%')";
            //else
            hidSelectedGroup.Value = NO_SELECT;
            RefreshCustomerGroup();
            updateGroup.Update();
            lstCustomer.Filter = Customers.ColumnNames.CustomerName + " LIKE '%" + txtSearchCust.Text + "%'";
            lstCustomer.Refresh();
        }

        protected void btnReload_OnClick(object sender, EventArgs e)
        {
            Reload();
        }

        protected void btnAddType_OnClick(object sender, EventArgs e)
        {
            RefreshCustomerGroup();
        }

        protected void btnRemoveType_OnClick(object sender, EventArgs e)
        {
            if (hidSelectedGroup.Value == "")
                return;
            if (!CustomerType.IsGroupEmpty(int.Parse(hidSelectedGroup.Value)))
            {
                ScriptManager.RegisterClientScriptBlock(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("alert('Can only delete empty Group!')", 1), true);
                return;
            }

            string oldFilter = GroupList.Filter;
            GroupList.Filter = CustomerType.ColumnNames.ID + "=" + hidSelectedGroup.Value;
            if (GroupList.RowCount > 0)
            {
                GroupList.Deleted = true;
                GroupList.LastModifiedByUser = SessionUser.ID;
                GroupList.LastModifiedDate = DateTime.UtcNow.AddHours(SysVars.TimeZone);
                GroupList.Save();
                GroupList.Filter = oldFilter;
                RefreshCustomerGroup();
            }
            else
                GroupList.Filter = oldFilter;
        }

        protected void gridFilterPaging_OnNeedListControl(object sender, EventArgs e)
        {
            gridFilterPaging.ListControl = lstCustomer;
        }

        public string PrintKey
        {
            get
            {
                if (ViewState["PrintKey"] == null)
                    ViewState["PrintKey"] = Guid.NewGuid().ToString();
                return ViewState["PrintKey"].ToString();
            }
        }

        public string GetPrintPage()
        {
            return "EditPages/PrintHandler.aspx?key=" + PrintKey;
        }
    }
}
